/*
 * DCE400服务系统 -- 后端服务接口 -- 数据访问层 -- 客户数据访问
 * 包括：客户数据库增删改查
 *      客户登录记录插入、查找
 */
package dao

import (
	"errors"
	entity2 "gitee.com/baal1990/gitee.com/baal1990/cmd/server/app/entity"
	"gitee.com/baal1990/gitee.com/baal1990/cmd/server/app/global"
	"gitee.com/baal1990/gitee.com/baal1990/pkg/db"
	"gitee.com/baal1990/gitee.com/baal1990/pkg/util"
	"go.uber.org/zap"
	"strings"
	"time"
)

//********************************************
//Func  ：查询注册协议
//Method：GET
//Usage ：注册 - 注册协议
//********************************************
func QueryRegistrationProtocol() (*entity2.Declaration, error) {
	var decaration entity2.Declaration
	_, err := db.Session().Table("declaration").Where("type=?", entity2.EDeclarationType_Registration).Get(&decaration)
	if err != nil {
		return nil, err
	}
	return &decaration, nil
}

//********************************************
//Func  ：查询平台须知
//Method：GET
//Usage ：注册
//********************************************
func QueryPlatformNotice() (*entity2.Declaration, error) {
	var decaration entity2.Declaration
	_, err := db.Session().Table("declaration").Where("type=?", entity2.EDeclarationType_Platform).Get(&decaration)
	if err != nil {
		return nil, err
	}
	return &decaration, nil
}

//********************************************
//Func  ：查询留言须知
//Method：GET
//Usage ：反馈
//********************************************
func QueryMessageNotice() (*entity2.Declaration, error) {
	var decaration entity2.Declaration
	_, err := db.Session().Table("declaration").Where("type=?", entity2.EDeclarationType_Message).Get(&decaration)
	if err != nil {
		return nil, err
	}
	return &decaration, nil
}

//********************************************
//Func  ：更新注册协议内容/没有则插入
//Method：POST
//Usage ：注册 - 注册协议
//********************************************
func UpdateDecarationInfo(decaration *entity2.Declaration) (*entity2.Declaration, error) {
	var err error
	cnt := int64(0)
	if decaration == nil {
		global.Log.Error("UpdateDecarationInfo: input is none")
		return nil, errors.New("input is none")
	}

	session := db.Session().Table("declaration")
	defer session.Close()
	var temp entity2.Declaration
	has, err := session.Where("type=?", decaration.Type).Get(&temp)
	if err != nil {
		global.Log.Error("UpdateDecarationInfo: Dao session.Get failed.", zap.Any("error", err))
		return nil, err
	}

	err = session.Begin()
	if err != nil {
		global.Log.Error("UpdateDecarationInfo: Dao session.Begin failed.", zap.Any("error", err))
		return nil, err
	}

	if has { //属于刷新操作
		if decaration.Id <= 0 {
			decaration.Id = temp.Id
		}
		decaration.EditedAt = time.Now()
		cnt, err = session.Cols("text,eng_text,describ,edited_at").
			Where("id=? and type=?", decaration.Id, decaration.Type).
			Update(decaration)
		global.Log.Info("UpdateDecarationInfo: Update", zap.Any("decaration:", decaration))
	} else {
		decaration.CreatedAt = time.Now()
		decaration.Id = util.GenSnowflakeInt64() //生成一个id
		cnt, err = session.Insert(decaration)    //插入
		global.Log.Info("UpdateDecarationInfo: Insert", zap.Any("decaration:", decaration))
	}

	if err != nil {
		session.Rollback()
		global.Log.Error("UpdateDecarationInfo session.Update failed", zap.Any("error:", err))
		return nil, err
	} else {
		err = session.Commit()
		global.Log.Info("UpdateDecarationInfo: success", zap.Any("decaration:", decaration), zap.Any("count:", cnt))
	}

	return decaration, err
}

//********************************************
//Func  ：查询子公司链接/友情链接 列表
//Method：GET
//Usage ：首页
//********************************************
func QueryFriendshipLinks(page, pageSize int, status entity2.EPublishStatus) (int64, []*entity2.FriendshipLink, error) {
	if page <= 0 {
		return 0, nil, errors.New("page error")
	}
	offset := (page - 1) * pageSize
	session := db.Session().Table("friendshiplink")
	defer session.Close()

	if pageSize > 0 {
		session.Limit(pageSize, offset)
	}

	if status >= entity2.EPublishStatus_Unpublished && status <= entity2.EPublishStatus_Deleted {
		session = session.Where("status=? and sort_index>=0", status).OrderBy("sort_index")
	} else {
		session = session.Where("sort_index>=0").OrderBy("sort_index")
	}
	global.Log.Info("QueryFriendshipLinks: ", zap.Any("status", status))

	links := []*entity2.FriendshipLink{}
	total, err := session.FindAndCount(&links)
	if err != nil {
		return 0, nil, err
	}
	return total, links, nil
}

//********************************************
//Func  ：新增子公司链接/友情链接
//Method：POST
//Usage ：首页
//********************************************
func InsertFriendshipLink(link *entity2.FriendshipLink) (*entity2.FriendshipLink, error) {
	if link == nil {
		global.Log.Error("InsertFriendshipLink: input is none")
		return nil, errors.New("input is none")
	}

	var err error
	link.CreatedAt = time.Now()
	link.PublishStatus = int(entity2.EPublishStatus_Unpublished) //未发布

	session := db.Session().Table("friendshiplink")
	defer session.Close()
	err = session.Begin()
	if err != nil {
		return nil, err
	}

	link.Id = util.GenSnowflakeInt64()
	global.Log.Info("InsertFriendshipLink: ", zap.Any("link:", link))

	_, err = session.Insert(link) //插入
	if err != nil {
		session.Rollback()
		return nil, err
	}

	err = session.Commit()
	if err != nil {
		global.Log.Error("InsertFriendshipLink commit failed, Error:", zap.Any("error", err))
	}

	var newlink entity2.FriendshipLink
	has, err := db.Session().Table("friendshiplink").Where("title=? and url=?", link.Title, link.Url).Desc("id").Get(&newlink) //
	if err != nil {
		return nil, err
	}
	if has {
		global.Log.Error("InsertFriendshipLink new success:", zap.Any("link", newlink))
	}
	return &newlink, nil
}

//********************************************
//Func  ：删除子公司链接/友情链接
//Method：DELETE
//Usage ：首页
//********************************************
func DeleteFriendshipLink(linkId int64) error {
	var err error
	var cnt int64
	global.Log.Info("DeleteFriendshipLink: Id:", zap.Any("id:", linkId))

	session := db.Session().Table("friendshiplink")
	defer session.Close()
	err = session.Begin()
	if err != nil {
		global.Log.Error("DeleteFriendshipLink begin failed, Error:", zap.Any("error", err))
		return err
	}

	cnt, err = session.Where("id=?", linkId).Delete(&entity2.FriendshipLink{}) //删除
	if err != nil {
		session.Rollback()
		global.Log.Error("DeleteFriendshipLink write db failed, Error:", zap.Any("error", err), zap.Any("cnt", cnt))
		return err
	}
	if cnt <= 0 {
		session.Rollback()
		return errors.New("linkId isnot exist.")
	}

	err = session.Commit()
	if err != nil {
		global.Log.Error("DeleteFriendshipLink dao commit failed, Error:", zap.Any("error", err))
	} else {
		global.Log.Info("DeleteFriendshipLink dao Delete success, del link:", zap.Any("linkId", linkId))
	}
	return err
}

//********************************************
//Func  ：更新子公司链接/友情链接
//Method：POST
//Usage ：首页
//********************************************
func UpdateFriendshipLink(link *entity2.FriendshipLink) (*entity2.FriendshipLink, error) {
	var err error
	var cnt int64
	if link == nil {
		return nil, errors.New("input is none")
	}

	session := db.Session().Table("friendshiplink")
	defer session.Close()
	if len(strings.TrimSpace(link.Title)) <= 0 {
		return nil, errors.New("title is none")
	}
	if len(strings.TrimSpace(link.Url)) <= 0 {
		return nil, errors.New("url is none")
	}

	global.Log.Info("UpdateFriendshipLink: ", zap.Any("link:", link))
	err = session.Begin()
	cnt, err = session.Cols("title,url,logo_url,sort_index").Where("id=?", link.Id).Update(link)
	if err != nil {
		global.Log.Error("UpdateFriendshipLink begin failed, Error:", zap.Any("error", err))
		return nil, err
	}

	err = session.Commit()
	if err != nil {
		global.Log.Error("UpdateFriendshipLink commit failed, Error:", zap.Any("error", err))
		return nil, err
	} else {
		global.Log.Info("UpdateFriendshipLink success, link:", zap.Any("link", link), zap.Any("count", cnt))
		return link, nil
	}
}

//********************************************
//Func  ：状态更新子公司链接/友情链接
//Method：POST
//Usage ：首页
//********************************************
func SetFriendshipLinkStatus(linkId int64, status int) error {
	var err error
	cnt := int64(0)
	if status < int(entity2.EPublishStatus_Unpublished) || status > int(entity2.EPublishStatus_Deleted) {
		return errors.New("unknown stauts")
	}

	var link entity2.FriendshipLink
	session := db.Session().Table("friendshiplink")
	defer session.Close()
	err = session.Begin()
	if err != nil {
		global.Log.Error("SetFriendshipLinkStatus begin failed, Error:", zap.Any("error", err))
		return err
	}
	link.Id = linkId
	link.PublishStatus = status
	cnt, err = session.Cols("publish_status").Where("id=?", link.Id).Update(&link)
	if err != nil {
		global.Log.Error("SetFriendshipLinkStatus update failed, Error:", zap.Any("error", err))
		return err
	}
	err = session.Commit()
	if err != nil {
		global.Log.Error("SetFriendshipLinkStatus commit failed, Error:", zap.Any("error", err))
	} else {
		global.Log.Info("SetFriendshipLinkStatus success:", zap.Any("link", link), zap.Any("count", cnt))
	}
	return err
}
